<template>
  <UserLayout :active-index="'2'" :active-menu="'landlord-center'">
    <div class="contract-content">
      <div class="contract-header">
        <el-button type="primary" @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回房东中心
        </el-button>
        <h2>签约管理</h2>
        <p>管理租客的签约申请和合同签署</p>
      </div>

      <!-- 签约申请列表 -->
      <div class="contract-list">
            <!-- 房东收到的签约申请 -->
            <el-card class="contract-card">
              <template #header>
                <div class="card-header">
                  <span>收到的签约申请</span>
                  <el-button type="primary" @click="refreshApplications">刷新</el-button>
                </div>
              </template>

              <div class="contract-list">
                <el-table :data="landlordApplications" style="width: 100%">
                  <el-table-column prop="houseTitle" label="房源信息" width="200"></el-table-column>
                  <el-table-column prop="tenantName" label="申请人" width="120"></el-table-column>
                  <el-table-column prop="applyTime" label="申请时间" width="150"></el-table-column>
                  <el-table-column prop="status" label="状态" width="120">
                    <template #default="scope">
                      <el-tag :type="getApplicationStatusType(scope.row.status)">
                        {{ getApplicationStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="leaseTerm" label="租期" width="100">
                    <template #default="scope">
                      {{ scope.row.leaseTerm }}个月
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="250">
                    <template #default="scope">
                      <el-button size="small" @click="viewApplicationDetail(scope.row)">查看详情</el-button>
                      <template v-if="scope.row.status === 'pending'">
                        <el-button size="small" type="success" @click="approveApplication(scope.row)">同意</el-button>
                        <el-button size="small" type="danger" @click="rejectApplication(scope.row)">拒绝</el-button>
                      </template>
                      <template v-else-if="scope.row.status === 'approved'">
                        <el-button size="small" type="primary" @click="viewContract(scope.row)">查看合同</el-button>
                      </template>
                      <template v-else-if="scope.row.status === 'tenant_rejected'">
                        <el-button size="small" type="info" @click="viewRejectionReason(scope.row)">查看拒绝理由</el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </div>
      </div>

    <!-- 申请详情对话框 -->
    <el-dialog
        v-model="showApplicationDetailDialog"
        title="申请详情"
        width="600px"
    >
      <div class="application-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="房源信息">{{ currentApplication?.houseTitle }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentApplication?.tenantName }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ currentApplication?.applyTime }}</el-descriptions-item>
          <el-descriptions-item label="租期">{{ currentApplication?.leaseTerm }}个月</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ currentApplication?.realName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ currentApplication?.identityCard }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentApplication?.phone }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getApplicationStatusType(currentApplication?.status)">
              {{ getApplicationStatusText(currentApplication?.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showApplicationDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 同意申请并拟定合同对话框 -->
    <el-dialog
        v-model="showContractDraftDialog"
        title="拟定合同"
        width="800px"
        :before-close="handleDraftDialogClose"
    >
      <div class="contract-draft-dialog">
        <h3>为 {{ currentApplication?.houseTitle }} 拟定合同</h3>

        <el-form :model="contractDraft" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="押金条款" prop="depositTerms" :rules="[{ required: true, message: '请输入押金条款', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.depositTerms"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入押金条款（通常为1-3个月租金，注明退还条件）"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房东义务" prop="landlordObligations" :rules="[{ required: true, message: '请输入房东义务', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.landlordObligations"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入房东义务"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租客义务" prop="tenantObligations" :rules="[{ required: true, message: '请输入租客义务', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.tenantObligations"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入租客义务"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="租客违约责任" prop="tenantDefault" :rules="[{ required: true, message: '请输入租客违约责任', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.tenantDefault"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入租客违约责任条款"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="房东违约责任" prop="landlordDefault" :rules="[{ required: true, message: '请输入房东违约责任', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.landlordDefault"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入房东违约责任条款"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="房屋维修条款" prop="houseMaintenance" :rules="[{ required: true, message: '请输入房屋维修条款', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.houseMaintenance"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入房屋维修条款"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同终止条款" prop="contractTermination" :rules="[{ required: true, message: '请输入合同终止条款', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.contractTermination"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入合同终止条款"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="争议解决" prop="disputeResolution" :rules="[{ required: true, message: '请输入争议解决方式', trigger: 'blur' }]">
                <el-input
                    v-model="contractDraft.disputeResolution"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入争议解决方式"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="保存为模板">
                <el-switch
                    v-model="contractDraft.saveAsTemplate"
                    active-text="是"
                    inactive-text="否"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDraft">取消</el-button>
          <el-button
              type="primary"
              @click="submitContractDraft"
              :disabled="!isDraftValid"
          >
            提交合同
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 合同生成进度对话框 -->
    <el-dialog
        v-model="showGeneratingDialog"
        title="合同生成中"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
    >
      <div class="generating-content">
        <div class="progress-container">
          <el-progress
              type="circle"
              :percentage="generationProgress"
              :status="generationStatus"
              :stroke-width="10"
              :width="120"
          />
        </div>
        <p class="progress-text">{{ generationText }}</p>
      </div>
    </el-dialog>

    <!-- 合同预览对话框 -->
    <el-dialog
        v-model="showContractPreviewDialog"
        title="合同预览"
        width="800px"
        :before-close="handlePreviewClose"
    >
      <div class="contract-preview">
        <h3>房屋租赁合同</h3>

        <div class="contract-section">
          <h4>一、基础信息条款</h4>

          <div class="contract-subsection">
            <h5>合同主体</h5>
            <p><strong>房东：</strong>{{ previewContract.landlordInfo?.name }}，身份证号：{{ previewContract.landlordInfo?.idCard }}，联系方式：{{ previewContract.landlordInfo?.phone }}</p>
            <p><strong>租客：</strong>{{ previewContract.tenantInfo?.name }}，身份证号：{{ previewContract.tenantInfo?.idCard }}，联系方式：{{ previewContract.tenantInfo?.phone }}</p>
          </div>

          <div class="contract-subsection">
            <h5>房屋信息</h5>
            <p><strong>地址：</strong>{{ previewContract.houseInfo?.address }}</p>
            <p><strong>建筑面积：</strong>{{ previewContract.houseInfo?.area }}</p>
            <p><strong>户型：</strong>{{ previewContract.houseInfo?.layout }}</p>
          </div>

          <div class="contract-subsection">
            <h5>租赁用途</h5>
            <p>仅限居住使用，禁止擅自改为群租房或违法用途。</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>二、租赁期限与费用</h4>

          <div class="contract-subsection">
            <h5>租期</h5>
            <p>起止日期：自{{ previewContract.startDate }}至{{ previewContract.endDate }}，租期{{ previewContract.leaseTerm }}个月。</p>
            <p>续约规则：租期满前30日书面协商续约。</p>
          </div>

          <div class="contract-subsection">
            <h5>租金与支付</h5>
            <p><strong>月租金：</strong>人民币{{ previewContract.rent }}元整</p>
            <p><strong>支付方式：</strong>银行转账</p>
            <p><strong>支付时间：</strong>每月5日前付清当月租金</p>
            <p><strong>押金条款：</strong>{{ previewContract.depositTerms }}</p>
          </div>

          <div class="contract-subsection">
            <h5>其他费用</h5>
            <p>水电燃气、物业费、网络费由租客自理。</p>
            <p>维修基金：小额维修由租客承担，大修由房东负责。</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>三、权利义务条款</h4>

          <div class="contract-subsection">
            <h5>房东义务</h5>
            <p>{{ previewContract.landlordObligations }}</p>
          </div>

          <div class="contract-subsection">
            <h5>租客义务</h5>
            <p>{{ previewContract.tenantObligations }}</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>四、违约责任</h4>

          <div class="contract-subsection">
            <h5>租客违约</h5>
            <p>{{ previewContract.tenantDefault }}</p>
          </div>

          <div class="contract-subsection">
            <h5>房东违约</h5>
            <p>{{ previewContract.landlordDefault }}</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>五、特殊条款</h4>

          <div class="contract-subsection">
            <h5>房屋维修</h5>
            <p>{{ previewContract.houseMaintenance }}</p>
          </div>

          <div class="contract-subsection">
            <h5>合同终止</h5>
            <p>{{ previewContract.contractTermination }}</p>
          </div>

          <div class="contract-subsection">
            <h5>争议解决</h5>
            <p>{{ previewContract.disputeResolution }}</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>六、其他必备条款</h4>

          <div class="contract-subsection">
            <h5>物品清单附件</h5>
            <p>详细记录家具、家电品牌及数量（避免退租纠纷）</p>
          </div>

          <div class="contract-subsection">
            <h5>物业交割单</h5>
            <p>水电燃气表底数、钥匙交付记录</p>
          </div>

          <div class="contract-subsection">
            <h5>合同生效条件</h5>
            <p>双方签字+押金/首期租金到账后生效</p>
          </div>
        </div>
      </div>

      <div class="agreement-section">
        <el-checkbox
            v-model="agreeToTerms"
            :disabled="!canCheckAgreement"
            @change="handleAgreementChange"
        >
          我已阅读并确认以上所有合同条款 ({{ canCheckAgreement ? '' : countdown + '秒后可勾选' }})
        </el-checkbox>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelContractPreview">取消</el-button>
          <el-button
              type="primary"
              @click="confirmContractPreview"
              :disabled="!agreeToTerms"
          >
            确认并提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog
        v-model="showContractDetailDialog"
        title="合同详情"
        width="800px"
    >
      <div class="contract-preview">
        <h3>房屋租赁合同</h3>

        <div class="contract-section">
          <h4>一、基础信息条款</h4>

          <div class="contract-subsection">
            <h5>合同主体</h5>
            <p><strong>房东：</strong>{{ currentApplication.landlordInfo?.name }}，身份证号：{{ currentApplication.landlordInfo?.idCard }}，联系方式：{{ currentApplication.landlordInfo?.phone }}</p>
            <p><strong>租客：</strong>{{ currentApplication.tenantInfo?.name }}，身份证号：{{ currentApplication.tenantInfo?.idCard }}，联系方式：{{ currentApplication.tenantInfo?.phone }}</p>
          </div>

          <div class="contract-subsection">
            <h5>房屋信息</h5>
            <p><strong>地址：</strong>{{ currentApplication.houseInfo?.address }}</p>
            <p><strong>建筑面积：</strong>{{ currentApplication.houseInfo?.area }}</p>
            <p><strong>户型：</strong>{{ currentApplication.houseInfo?.layout }}</p>
          </div>

          <div class="contract-subsection">
            <h5>租赁用途</h5>
            <p>仅限居住使用，禁止擅自改为群租房或违法用途。</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>二、租赁期限与费用</h4>

          <div class="contract-subsection">
            <h5>租期</h5>
            <p>起止日期：自{{ currentApplication.startDate }}至{{ currentApplication.endDate }}，租期{{ currentApplication.leaseTerm }}个月。</p>
            <p>续约规则：租期满前30日书面协商续约。</p>
          </div>

          <div class="contract-subsection">
            <h5>租金与支付</h5>
            <p><strong>月租金：</strong>人民币{{ currentApplication.rent }}元整</p>
            <p><strong>支付方式：</strong>银行转账</p>
            <p><strong>支付时间：</strong>每月5日前付清当月租金</p>
            <p><strong>押金条款：</strong>{{ currentApplication.depositTerms }}</p>
          </div>

          <div class="contract-subsection">
            <h5>其他费用</h5>
            <p>水电燃气、物业费、网络费由租客自理。</p>
            <p>维修基金：小额维修由租客承担，大修由房东负责。</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>三、权利义务条款</h4>

          <div class="contract-subsection">
            <h5>房东义务</h5>
            <p>{{ currentApplication.landlordObligations }}</p>
          </div>

          <div class="contract-subsection">
            <h5>租客义务</h5>
            <p>{{ currentApplication.tenantObligations }}</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>四、违约责任</h4>

          <div class="contract-subsection">
            <h5>租客违约</h5>
            <p>{{ currentApplication.tenantDefault }}</p>
          </div>

          <div class="contract-subsection">
            <h5>房东违约</h5>
            <p>{{ currentApplication.landlordDefault }}</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>五、特殊条款</h4>

          <div class="contract-subsection">
            <h5>房屋维修</h5>
            <p>{{ currentApplication.houseMaintenance }}</p>
          </div>

          <div class="contract-subsection">
            <h5>合同终止</h5>
            <p>{{ currentApplication.contractTermination }}</p>
          </div>

          <div class="contract-subsection">
            <h5>争议解决</h5>
            <p>{{ currentApplication.disputeResolution }}</p>
          </div>
        </div>

        <div class="contract-section">
          <h4>六、其他必备条款</h4>

          <div class="contract-subsection">
            <h5>物品清单附件</h5>
            <p>详细记录家具、家电品牌及数量（避免退租纠纷）</p>
          </div>

          <div class="contract-subsection">
            <h5>物业交割单</h5>
            <p>水电燃气表底数、钥匙交付记录</p>
          </div>

          <div class="contract-subsection">
            <h5>合同生效条件</h5>
            <p>双方签字+押金/首期租金到账后生效</p>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showContractDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 拒绝申请对话框 -->
    <el-dialog
        v-model="showRejectDialog"
        title="拒绝申请"
        width="500px"
    >
      <el-form>
        <el-form-item label="拒绝理由">
          <el-input
              v-model="rejectReason"
              type="textarea"
              :rows="4"
              placeholder="请输入拒绝理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRejectDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmReject">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 拒绝理由查看对话框 -->
    <el-dialog
        v-model="showRejectionReasonDialog"
        title="拒绝理由"
        width="500px"
    >
      <el-form>
        <el-form-item label="拒绝理由">
          <el-input
              v-model="rejectionReason"
              type="textarea"
              :rows="4"
              placeholder="拒绝理由"
              readonly
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRejectionReasonDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </UserLayout>
</template>

<script setup>
import { ref, reactive, computed, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import { ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()

// 返回房东中心
const goBack = () => {
  router.push('/rental/landlord')
}
const showApplicationDetailDialog = ref(false)
const showContractDraftDialog = ref(false)
const showGeneratingDialog = ref(false)
const showContractPreviewDialog = ref(false)
const showContractDetailDialog = ref(false)
const showRejectDialog = ref(false)
const showRejectionReasonDialog = ref(false)
const rejectReason = ref('')
const rejectionReason = ref('')
const currentApplication = ref(null)
const generationProgress = ref(0)
const generationStatus = ref('')
const generationText = ref('正在生成合同...')
let generationInterval = null
const agreeToTerms = ref(false)
const canCheckAgreement = ref(false)
const countdown = ref(5)
let countdownInterval = null

// 房东收到的签约申请
const landlordApplications = ref([
  {
    id: 101,
    houseTitle: '精致一居室公寓',
    tenantName: '张三',
    applyTime: '2023-06-15 14:30',
    leaseTerm: 12,
    realName: '张三',
    identityCard: '110101199001011234',
    phone: '13812345678',
    status: 'pending', // pending, approved, rejected, tenant_rejected
    landlordInfo: {
      name: '李四',
      idCard: '110101199002021234',
      phone: '139****9999'
    },
    tenantInfo: {
      name: '张三',
      idCard: '110101199001011234',
      phone: '138****8888'
    },
    houseInfo: {
      address: '北京市朝阳区CBD建国路123号',
      area: '60㎡',
      layout: '一室一厅'
    },
    startDate: '2023-07-01',
    endDate: '2024-06-30',
    rent: 4500
  },
  {
    id: 102,
    houseTitle: '豪华两居室',
    tenantName: '李四',
    applyTime: '2023-06-12 11:20',
    leaseTerm: 24,
    realName: '李四',
    identityCard: '110101199002021234',
    phone: '13987654321',
    status: 'approved',
    landlordInfo: {
      name: '王五',
      idCard: '110101199003031234',
      phone: '137****7777'
    },
    tenantInfo: {
      name: '李四',
      idCard: '110101199002021234',
      phone: '139****9999'
    },
    houseInfo: {
      address: '北京市朝阳区三里屯太古里456号',
      area: '90㎡',
      layout: '两室一厅'
    },
    startDate: '2023-07-15',
    endDate: '2025-07-14',
    rent: 8500,
    depositTerms: '押金为两个月租金，退租时房屋设施无损坏且结清水电费后退还',
    landlordObligations: '交房时保证房屋无产权纠纷，设施正常使用，配合办理暂住证等手续',
    tenantObligations: '禁止转租/分租，不得擅自拆改房屋结构，禁止堆放易燃易爆物品',
    tenantDefault: '逾期支付租金：按日加收2%滞纳金，超15日可解除合同；提前退租：扣减押金或支付2个月租金作为违约金',
    landlordDefault: '无故收回房屋：赔偿租客2个月租金+搬家费；未履行维修义务：租客可自行维修并抵扣租金',
    houseMaintenance: '自然损坏由房东负责（如水管老化破裂）；人为损坏由租客承担（如打碎玻璃窗）',
    contractTermination: '租客退租需提前30日书面通知，并结清费用；房东售房需提前60日通知，租客享有优先购买权',
    disputeResolution: '协商不成时，向房屋所在地法院提起诉讼'
  },
  {
    id: 103,
    houseTitle: '舒适三居室',
    tenantName: '王五',
    applyTime: '2023-06-10 09:45',
    leaseTerm: 12,
    realName: '王五',
    identityCard: '110101199003031234',
    phone: '13698765432',
    status: 'tenant_rejected',
    landlordInfo: {
      name: '赵六',
      idCard: '110101199004041234',
      phone: '135****5555'
    },
    tenantInfo: {
      name: '王五',
      idCard: '110101199003031234',
      phone: '136****6666'
    },
    houseInfo: {
      address: '北京市朝阳区国贸SOHO789号',
      area: '120㎡',
      layout: '三室两厅'
    },
    startDate: '2023-07-01',
    endDate: '2024-06-30',
    rent: 12000,
    depositTerms: '押金为两个月租金，退租时房屋设施无损坏且结清水电费后退还',
    landlordObligations: '交房时保证房屋无产权纠纷，设施正常使用，配合办理暂住证等手续',
    tenantObligations: '禁止转租/分租，不得擅自拆改房屋结构，禁止堆放易燃易爆物品',
    tenantDefault: '逾期支付租金：按日加收2%滞纳金，超15日可解除合同；提前退租：扣减押金或支付2个月租金作为违约金',
    landlordDefault: '无故收回房屋：赔偿租客2个月租金+搬家费；未履行维修义务：租客可自行维修并抵扣租金',
    houseMaintenance: '自然损坏由房东负责（如水管老化破裂）；人为损坏由租客承担（如打碎玻璃窗）',
    contractTermination: '租客退租需提前30日书面通知，并结清费用；房东售房需提前60日通知，租客享有优先购买权',
    disputeResolution: '协商不成时，向房屋所在地法院提起诉讼',
    rejectionReason: '租金太高，无法接受'
  }
])

// 合同草案
const contractDraft = reactive({
  depositTerms: '押金为两个月租金，退租时房屋设施无损坏且结清水电费后退还',
  landlordObligations: '交房时保证房屋无产权纠纷，设施正常使用，配合办理暂住证等手续（如需）',
  tenantObligations: '禁止转租/分租（或约定转租需房东书面同意），不得擅自拆改房屋结构，卫生及安全管理（如"禁止堆放易燃易爆物品"）',
  tenantDefault: '①租客违约：逾期支付租金：按日加收2%滞纳金，超15日可解除合同；提前退租：扣减押金或支付2个月租金作为违约金',
  landlordDefault: '②房东违约：无故收回房屋：赔偿租客2个月租金+搬家费；未履行维修义务：租客可自行维修并抵扣租金',
  houseMaintenance: '①房屋维修：自然损坏：房东负责（如水管老化破裂）；人为损坏：租客承担（如打碎玻璃窗）',
  contractTermination: '②合同终止：租客退租需提前30日书面通知，并结清费用；房东售房需提前60日通知，租客享有优先购买权',
  disputeResolution: '协商不成时，向房屋所在地法院提起诉讼',
  saveAsTemplate: true
})

// 预览合同
const previewContract = ref({})

// 检查草案是否有效
const isDraftValid = computed(() => {
  return contractDraft.depositTerms &&
      contractDraft.landlordObligations &&
      contractDraft.tenantObligations &&
      contractDraft.tenantDefault &&
      contractDraft.landlordDefault &&
      contractDraft.houseMaintenance &&
      contractDraft.contractTermination &&
      contractDraft.disputeResolution
})

// 获取申请状态类型
const getApplicationStatusType = (status) => {
  const statusTypes = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'tenant_rejected': 'info'
  }
  return statusTypes[status] || 'info'
}

// 获取申请状态文本
const getApplicationStatusText = (status) => {
  const statusTexts = {
    'pending': '待处理',
    'approved': '已同意',
    'rejected': '已拒绝',
    'tenant_rejected': '租客已拒绝'
  }
  return statusTexts[status] || '未知状态'
}

// 顶部导航栏跳转
const goToHome = () => {
  router.push('/')
}

const goToSearch = () => {
  router.push('/house/search')
}

const goToPublish = () => {
  router.push('/house/publish')
}

const goToMessages = () => {
  router.push('/message')
}

// 用户命令处理
const handleUserCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      ElMessage.success('退出登录成功')
      localStorage.removeItem('userEmail')
      localStorage.removeItem('isLoggedIn')
      router.push('/login')
      break
  }
}

// 侧边栏跳转
const goToPublishNew = () => {
  router.push('/house/publish')
}

const goToMyHouses = () => {
  router.push('/house/my-houses')
}

const goToAgentApply = () => {
  router.push('/agent/apply')
}

const goToAgentStatus = () => {
  router.push('/agent/status')
}

const goToAgentHouses = () => {
  router.push('/agent/houses')
}

const goToTenant = () => {
  router.push('/rental/tenant')
}

const goToLandlord = () => {
  router.push('/rental/landlord')
}

const goToAgentRental = () => {
  router.push('/rental/agent')
}

const goToContract = () => {
  router.push('/contract/landlord')
}

const goToProfile = () => {
  router.push('/profile')
}

// 菜单选择处理
const handleSelect = (key) => {
  switch (key) {
    case '1':
      router.push('/')
      break
    case '2':
      router.push('/house/search')
      break
    case '3':
      router.push('/house/publish')
      break
    case '4':
      router.push('/message')
      break
  }
}

// 刷新申请列表
const refreshApplications = () => {
  ElMessage.success('刷新成功')
}

// 查看申请详情
const viewApplicationDetail = (application) => {
  currentApplication.value = application
  showApplicationDetailDialog.value = true
}

// 同意申请
const approveApplication = (application) => {
  ElMessageBox.confirm(
      '确定要同意该签约申请吗？',
      '同意申请',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 显示合同拟定对话框
    currentApplication.value = application
    showContractDraftDialog.value = true
  }).catch(() => {
    // 用户取消操作
  })
}

// 处理拟定对话框关闭
const handleDraftDialogClose = (done) => {
  ElMessageBox.confirm('确定要取消拟定合同吗？')
      .then(() => {
        done()
      })
      .catch(() => {
        // 用户取消关闭
      })
}

// 取消拟定合同
const cancelDraft = () => {
  showContractDraftDialog.value = false
  currentApplication.value = null
}

// 提交合同草案
const submitContractDraft = () => {
  // 检查表单是否填写完整
  if (!isDraftValid.value) {
    ElMessage.error('请填写所有必填项')
    return
  }

  // 关闭拟定对话框
  showContractDraftDialog.value = false

  // 显示生成进度对话框
  showGeneratingDialog.value = true
  generationProgress.value = 0
  generationStatus.value = ''
  generationText.value = '正在生成合同...'

  // 模拟生成进度
  generationInterval = setInterval(() => {
    generationProgress.value += 10
    if (generationProgress.value >= 100) {
      clearInterval(generationInterval)
      generationStatus.value = 'success'
      generationText.value = '合同生成完成'

      // 延迟显示预览对话框
      setTimeout(() => {
        showGeneratingDialog.value = false
        showPreviewContract()
      }, 1000)
    }
  }, 300)
}

// 显示预览合同
const showPreviewContract = () => {
  // 构建预览合同数据
  previewContract.value = {
    ...currentApplication.value,
    ...contractDraft
  }

  // 显示预览对话框
  showContractPreviewDialog.value = true
  agreeToTerms.value = false
  canCheckAgreement.value = false
  countdown.value = 5

  // 开始倒计时
  countdownInterval = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      canCheckAgreement.value = true
      clearInterval(countdownInterval)
    }
  }, 1000)
}

// 处理协议勾选变化
const handleAgreementChange = (val) => {
  agreeToTerms.value = val
}

// 取消合同预览
const cancelContractPreview = () => {
  showContractPreviewDialog.value = false
  clearInterval(countdownInterval)
}

// 处理预览对话框关闭
const handlePreviewClose = (done) => {
  ElMessageBox.confirm('确定要取消合同预览吗？')
      .then(() => {
        clearInterval(countdownInterval)
        done()
      })
      .catch(() => {
        // 用户取消关闭
      })
}

// 确认合同预览
const confirmContractPreview = () => {
  // 更新申请状态为已同意并添加合同条款
  const index = landlordApplications.value.findIndex(item => item.id === currentApplication.value.id)
  if (index > -1) {
    landlordApplications.value[index].status = 'approved'
    landlordApplications.value[index] = {
      ...landlordApplications.value[index],
      ...contractDraft
    }
  }

  ElMessage.success('合同已提交，请等待租客签署')
  showContractPreviewDialog.value = false
  currentApplication.value = null
  clearInterval(countdownInterval)
}

// 拒绝申请
const rejectApplication = (application) => {
  currentApplication.value = application
  rejectReason.value = ''
  showRejectDialog.value = true
}

// 确认拒绝
const confirmReject = () => {
  if (!rejectReason.value.trim()) {
    ElMessage.error('请输入拒绝理由')
    return
  }

  // 更新申请状态为已拒绝
  const index = landlordApplications.value.findIndex(item => item.id === currentApplication.value.id)
  if (index > -1) {
    landlordApplications.value[index].status = 'rejected'
    landlordApplications.value[index].rejectionReason = rejectReason.value
  }

  ElMessage.success('已拒绝该签约申请')
  showRejectDialog.value = false
}

// 查看合同
const viewContract = (application) => {
  currentApplication.value = application
  showContractDetailDialog.value = true
}

// 查看拒绝理由
const viewRejectionReason = (application) => {
  rejectionReason.value = application.rejectionReason
  showRejectionReasonDialog.value = true
}

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  if (generationInterval) {
    clearInterval(generationInterval)
  }
  if (countdownInterval) {
    clearInterval(countdownInterval)
  }
})
</script>

<style scoped>
.contract-container {
  display: flex;
  min-height: 100vh;
  overflow: hidden;
  position: relative;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

/* 精美的动态背景 */
.dynamic-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

.building-1 {
  left: 10%;
  width: 80px;
  height: 300px;
  animation: buildingGlow 4s infinite alternate;
}

.building-2 {
  left: 25%;
  width: 120px;
  height: 400px;
  animation: buildingGlow 5s infinite alternate-reverse;
}

.building-3 {
  left: 45%;
  width: 100px;
  height: 350px;
  animation: buildingGlow 6s infinite alternate;
}

.building-4 {
  left: 65%;
  width: 140px;
  height: 450px;
  animation: buildingGlow 4.5s infinite alternate-reverse;
}

.building-5 {
  left: 80%;
  width: 90px;
  height: 320px;
  animation: buildingGlow 5.5s infinite alternate;
}

@keyframes buildingGlow {
  0% {
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
  }
  100% {
    box-shadow: 0 -5px 25px rgba(100, 200, 255, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  filter: blur(2px);
}

.cloud-1 {
  top: 20%;
  left: 5%;
  width: 80px;
  height: 30px;
  animation: cloudMove 25s linear infinite;
}

.cloud-2 {
  top: 35%;
  left: 70%;
  width: 120px;
  height: 40px;
  animation: cloudMove 30s linear infinite;
}

.cloud-3 {
  top: 15%;
  left: 40%;
  width: 100px;
  height: 35px;
  animation: cloudMove 35s linear infinite;
}

@keyframes cloudMove {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

/* 太阳 */
.sun {
  position: absolute;
  top: 80px;
  right: 100px;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, #ffeb3b, #ffc107);
  border-radius: 50%;
  box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  animation: sunPulse 3s infinite alternate;
}

@keyframes sunPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 0 60px #ff9800, 0 0 100px #ff5722;
  }
}

/* 光线 */
.light-ray {
  position: absolute;
  top: 120px;
  right: 140px;
  width: 400px;
  height: 200px;
  background: linear-gradient(to right, transparent, rgba(255, 235, 59, 0.2), transparent);
  transform-origin: left center;
  animation: rayRotate 10s infinite linear;
}

.ray-1 {
  transform: rotate(0deg);
  animation-delay: 0s;
}

.ray-2 {
  transform: rotate(60deg);
  animation-delay: 2s;
}

.ray-3 {
  transform: rotate(120deg);
  animation-delay: 4s;
}

@keyframes rayRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 浮动装饰元素 */
.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  right: -80px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

.shape-5 {
  width: 250px;
  height: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-duration: 22s;
  background: radial-gradient(circle, rgba(155, 89, 182, 0.2) 0%, transparent 70%);
}

.shape-6 {
  width: 180px;
  height: 180px;
  top: 70%;
  left: 10%;
  animation-duration: 28s;
  background: radial-gradient(circle, rgba(231, 76, 60, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.contract-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  z-index: 1;
  position: relative;
}

.top-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 30px;
  background: rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.app-title {
  color: white;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
}

.navbar-center {
  flex: 1;
  margin: 0 20px;
}

:deep(.el-menu--horizontal) {
  border: none;
  background: transparent !important;
}

:deep(.el-menu--horizontal .el-menu-item) {
  color: white;
  border: none;
}

:deep(.el-menu--horizontal .el-menu-item:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.el-menu--horizontal .el-menu-item.is-active) {
  color: #4A90E2 !important;
  border: none;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: white;
}

.username {
  font-size: 16px;
  font-weight: 500;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  padding: 20px 0;
  height: 100%;
  box-shadow: 3px 0 10px rgba(0, 0, 0, 0.2);
}

.el-menu-vertical {
  border: none !important;
  height: 100%;
}

.el-menu-item,
.el-sub-menu__title {
  margin: 5px 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-menu-item:hover,
.el-sub-menu__title:hover {
  background-color: rgba(255, 255, 255, 0.1) !important;
}

.content-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  overflow-y: auto;
  padding: 20px;
}

.contract-header {
  margin-bottom: 30px;
}

.contract-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0 0 10px;
}

.contract-header p {
  color: #7f8c8d;
  margin: 0;
}

.contract-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.contract-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.contract-list :deep(.el-table) {
  margin-top: 20px;
}

.application-detail :deep(.el-descriptions__label) {
  width: 100px;
}

.contract-draft-dialog h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #2c3e50;
}

.contract-draft-dialog :deep(.el-form-item) {
  margin-bottom: 25px;
}

.generating-content {
  text-align: center;
  padding: 30px 0;
}

.progress-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.progress-text {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0;
}

.contract-preview {
  max-height: 500px;
  overflow-y: auto;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  background: #fafafa;
}

.contract-preview h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #2c3e50;
}

.contract-section {
  margin-bottom: 20px;
}

.contract-section h4 {
  margin: 0 0 15px;
  color: #2c3e50;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.contract-subsection {
  margin-bottom: 15px;
}

.contract-subsection h5 {
  margin: 0 0 8px;
  color: #2c3e50;
}

.contract-subsection p {
  margin: 0 0 5px;
  color: #7f8c8d;
  line-height: 1.5;
}

.agreement-section {
  margin: 20px 0;
  padding: 15px;
  background: #f0f9ff;
  border-radius: 8px;
  border: 1px solid #b3d9ff;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .app-title,
  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .contract-header {
    text-align: center;
  }

  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}
</style>
